#include "stdafx.h"
#include "./playermgr.h"

PlayerThread* PlayerMgr::s_pThreads[MAX_PLAYER_COUNT];
vector<Player*> PlayerMgr::s_playerList;
int PlayerMgr::s_count = 0;

PlayerMgr::PlayerMgr()
{
	memset(s_pThreads, 0, sizeof(PlayerThread*) * MAX_PLAYER_COUNT);
}

PlayerMgr::~PlayerMgr()
{
}

void PlayerMgr::Start()
{
	for (int i = 0; i < s_count; ++i)
	{
		s_pThreads[i]->Start();
	}
}

void PlayerMgr::Stop()
{
	for (int i = 0; i < s_count; ++i)
	{
		if (!s_pThreads[i]->GetStarted())
		{
			delete s_pThreads[i];
			s_pThreads[i] = NULL;
		}
		else
		{
			s_pThreads[i]->Stop();
		}
	}

	s_count = 0;
	s_playerList.clear();
}

int PlayerMgr::AddPlayer(string strName, 
			  Point startPos, 
			  float startAngle, 
			  Point hpPos,
			  float z,
			  Color color)
{
	if (s_count == MAX_PLAYER_COUNT)
	{
		return -1;
	}

	int index = s_count;

	s_pThreads[index] = new PlayerThread();
	s_pThreads[index]->Init(index, strName, startPos, startAngle, hpPos, z, color);
	s_pThreads[index]->OnThreadEnd += EventObject<OnThreadEndFunc>(this, &PlayerMgr::OnPlayerThreadEnd);

	s_playerList.push_back(s_pThreads[index]->GetPlayer());
	s_count++;

	return index;
}

vector<Player*>& PlayerMgr::GetPlayers()
{
	return s_playerList;
}

void PlayerMgr::OnPlayerThreadEnd(BaseThread* pThread)
{
	for (int i = 0; i < MAX_PLAYER_COUNT; ++i)
	{
		if (s_pThreads[i] == pThread)
		{
			delete s_pThreads[i];
			s_pThreads[i] = NULL;
		}
	}
}